package umls.interfaces.pubmed.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;

import org.apache.log4j.Logger;

public class FileFlusher implements Runnable {
	static Logger logger = Logger.getLogger("umls.interfaces.pubmed.server");
	private final BlockingQueue<MetamapOutput> input;
	String prefix;

	public FileFlusher(BlockingQueue<MetamapOutput> in, String p) {
		input = in;
		prefix = p;
	}

	public void run() {
		try {
			flushtoDir(input.take(), prefix);
		} catch (InterruptedException e) {
			System.out.println("Errore nel writer " + e.getMessage());
			e.printStackTrace();
		} catch (ExecutionException e) {
			System.out.println("Errore nel writer " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Errore nel writer " + e.getMessage());
			e.printStackTrace();
		}
	}

	private void flushtoDir(MetamapOutput out, String prefix)
			throws InterruptedException, ExecutionException, IOException {

		if (out == null || prefix == null) {
			logger.error("Errore parametri flusher--> MetamapOutput = " + out
					+ " prefix = " + prefix);
			System.out.println("Errore parametri flusher--> MetamapOutput = "
					+ out + " prefix = " + prefix);
			return;
		}
		if (out.getAbstrs() == null || out.getAbstrs().isEmpty())
			return;
		StringBuffer sb = new StringBuffer(prefix + "/"
				+ out.getKeys()[0].replace("+", "_"));
		for (int i = 1; i < out.getKeys().length; i++)
			sb.append("_" + out.getKeys()[i].replace("+", "_"));
		String path = sb.toString();
		for (PubMedAbstractMapped abstr : out.getAbstrs()) {
			File f = new File(path + "_" + abstr.getId() + ".txt");
			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			for (String result : abstr.getAbstract()) {
				output.write(result + "\n");
			}
			output.flush();
			output.close();

		}
		logger.trace("Scritta famiglia di file " + prefix);
	}
}
